
// Copyright (C) 2007 Richard Uhler
// This file is part of Esiply.
//
// Esiply is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License, Version 2,
// as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

#include "Boolean.h"
#include "ConditionalExpression.h"
#include "Value.h"

ConditionalExpression::ConditionalExpression(Expression* cond,
        Expression* true_exp, Expression* false_exp)
    : m_cond(cond), m_true(true_exp), m_false(false_exp)
{}

Value* ConditionalExpression::evaluate(Scope* scope)
{
    // Ecma 11.12
    // 1. Evaluate condition
    // 2. Call get value on the result
    Value* cond = m_cond->evaluate(scope)->getValue();
    CHECK_EXCEPTION(cond);

    // 3. Call to boolean 
    Boolean* bcond = cond->toBoolean();
    CHECK_EXCEPTION(bcond);

    // 4. If result is false, go to step 8
    if (bcond->isTrue())
    {
        // 5. Evaluate m_true
        // 6. Call getValue on that.
        // 7. Return it
        return m_true->evaluate(scope)->getValue();
    }

    // 8. evaluate false
    // 9. call get value on that
    // 10. return result
    return m_false->evaluate(scope)->getValue();
}

